package per.zqx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import per.zqx.mapper.OrderMapper;
import per.zqx.pojo.Order;
import per.zqx.pojo.OrderMessage;
import per.zqx.service.OrderMessageService;
import per.zqx.service.OrderService;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * OrderServiceImpl,
 *
 * @author Sa, Zhang 2021-08-15 16:41
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderMessageService messageService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void regCallback(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("cause: " + cause);
                Long orderId = Long.valueOf(Objects.requireNonNull(correlationData.getId()));
                if (!ack){
                    System.out.println("MQ 应答失败，orderId 是： " + orderId);
                    return;
                }
                try {
                    messageService.update(orderId);
                    System.out.println("本地修改状态成功，消息已经投递到队列");
                }catch (Exception e){
                    System.out.println("本地修改消息状态失败，异常：" + e);
                }
            }
        });
    }

    @Override
    public Order get(Long orderId) {
        return orderMapper.findById(orderId).orElse(null);
    }

    @Override
    public void add(Order order) {
        Order save = orderMapper.save(order);
        OrderMessage orderMessage = messageService.add(save);
        sendMessage(save);
    }

    public void sendMessage(Order order){
        String exchange = "acid_order_exchange";
        String routerKey = "";
        JSONObject o = (JSONObject) JSONObject.toJSON(order);
        String orderMsg = o.toJSONString();
        rabbitTemplate.convertAndSend(exchange,routerKey,orderMsg ,new CorrelationData(String.valueOf(order.getId())));
    }
}
